
document.body.onload = function () {
    const appid = "wxe24bd457c01631f8";
    const url = "https://ikapi.mad-sea.com";
    const userinfoApi = "/api/h5user/userinfo";
    const usersApi = "/Api/H5User/Users";
    const scoreApi = "/api/h5user/score";
    const rankApi = "/api/h5user/rank";
    let TOKEN = "";
    let isRegister = false; // 是否注册过


    /**
     * canvas
     * stage
     * container 主要容器
     * stageWidth 舞台宽度
     */
    var canvas, stage, container, stageWidth, stageHeight, stageScale, images = {}, paused, music;
    var loadC, loadBg, loadP, loadT;
    var bg, bg2, b1, b2, bgSpeed = 4, timeBg, scoreBg, runLine;
    // p1StartBtn 开始游戏按钮
    var p1C, p1Bg, p1StartBtn, p1Title, p1T, p1Car, p1S, p1P, p1RuleBtn, p1L1, p1L2, p1L3, p1L4, p1L5, p1L6, p1L7, p1L8, p1L9, p1L10, p1L11, activityPB, activityPBtn;
    var rPC, reStartBtn;
    // var penWidth = 106.6;
    // var penHeight = 135;

    // person的宽高
    var penWidth = 281;
    var penHeight = 192;
    var penY;
    var pen = function () { };

    var msb_num_left = 0;
    var cxs_num_left = 0;
    var sxd_num_left = 0;
    var zad_num_left = 0;
    var love_num_left = 0;
    var lumi_num_left = 0;
    var bodyspa_num_left = 0;
    var score = 0;
    var scoreValue = 0;
    var isEnd = false;
    var time = 30; // TODO 游戏时间
    // var time = 5; // 游戏时间
    var timer; // 游戏时间定时器
    var gameTime; // createjs游戏时间
    var sound;
    var body;
    var hard = 0; // 难度值
    var speed = 0;

    var money;
    var green10 = new Image(); //ageLocme
    green10.src = "html/images/score-green10.png";

    var lightblue20 = new Image(); //spa
    lightblue20.src = "html/images/score-lightblue20.png";

    var blue30 = new Image(); //accent
    blue30.src = "html/images/score-blue30.png";

    var red40 = new Image(); //爱心
    red40.src = "html/images/score-red40.png";

    var gold70 = new Image(); //gold70
    gold70.src = "html/images/score-gold70.png";

    var bodyspa = new Image(); //bodyspa
    bodyspa.src = "html/images/bodyspa.png";

    var black_20 = new Image(); //炸弹
    black_20.src = "html/images/score-black-20.png";

    var moneyEnum = { // 给元素设置初始化值 图片路径，元素掉落速度，元素得分，各自num
        green10: {
            image: green10, //ageLocme
            speed: 15,
            value: 10,
            num: 50
        },
        lightblue20: {
            image: lightblue20, //facespa
            speed: 15,
            value: 20,
            num: 50
        },
        blue30: {
            image: blue30, //accent
            speed: 10,
            value: 30,
            num: 30
        },
        red40: {
            image: red40, //爱心
            speed: 10,
            value: 40,
            num: 12
        },
        gold70: {
            image: gold70, //gold70
            speed: 10,
            value: 70,
            num: 12
        },
        black_20: {
            image: black_20, //炸弹
            speed: 5,
            value: -20,
            num: 1000
        },

        bodyspa: {
            image: bodyspa, //bodyspa
            speed: 10,
            value: 30,
            num: 50
        },
    };
    // 小人雪碧图
    var ss = new createjs.SpriteSheet({
        "images": ['html/images/person.png'],
        "frames": {
            "width": 281,
            "height": 192,
            "count": 1,
        },
        "animations": {
            "stand": [0, 0, 'stand', .2],
            "run": [0, 0, 'stand', .3]
        }
    });
    var person = new createjs.Sprite(ss, 'stand');
    var f = new createjs.Text(score, 'bold 24px Arial', '#fff'); //右上角分数

    music = $('#music')[0]; // 绑定音乐

    // 开始加载游戏
    function init() {
        canvas = document.getElementById("mainView");
        stage = new createjs.Stage(canvas);
        container = new createjs.Container();
        stage.addChild(container);
        createjs.Touch.enable(stage);
        bg = cBitmap('html/images/game_bg.jpg'); // 游戏背景
        bg2 = cBitmap('html/images/game_bg.jpg'); // 第二个背景图
        timeBg = cBitmap('html/images/time_bg.png'); // 游戏的时间背景
        timeBg.y = 20;
        scoreBg = cBitmap('html/images/score_bg.png'); // 游戏的分数背景
        // scoreBg.x = 20;
        scoreBg.y = 20;
        // runLine = cBitmap('html/images/run_line.png'); // 下方人行道
        container.addChild(bg);
        p1C = new createjs.Container();

        createjs.Ticker.timingMode = createjs.Ticker.RAF_SYNCHED;
        createjs.Ticker.setFPS(30);

        stageBreakHandler(); //适配
        scoreBg.x = stageWidth - 158; // 分数背景的位置
        // runLine.y = stageHeight - 117; // 最下方线的位置
        // runLine.x = 40;

        paused = createjs.Ticker.paused = true;
        createjs.Ticker.addEventListener("tick", function (e) {
            paused && stage.update();
            if (isEnd) {
                body.draw();
            }
        });

        loadFun();

        pen.prototype.draw = function () { // 不断位置跑步小人
            this.penE = person;
            // this.penE.x = 106.6;
            this.penE.x = 281;
            this.penE.y = stageHeight - 135 - 117;
            // stage.addChild(this.penE);
        };

        function Body() {
            var that = this;
            this.moneyList = [];
            this.mainpen = new pen();

            stage.addEventListener('mousedown', touch, false);
            stage.addEventListener('pressmove', touch, false);
            stage.addEventListener('pressup', touch, false);

            var touchx;
            function touch(event) { // 拖动元素
                var e = event || window.event;
                switch (e.type) {
                    case "mousedown":
                        touchx = e.stageX - penWidth / 2;
                        break;
                    case "pressup":
                        touchx = e.stageX - penWidth / 2;
                        if (touchx < 0) { // 不让元素超过左边
                            touchx = 0;
                        }
                        if (touchx > stageWidth - penWidth) {// 不让元素超过右边
                            touchx = stageWidth - penWidth;
                        }
                        that.mainpen.penE.x = touchx;
                        break;
                    case "pressmove":
                        e.preventDefault();
                        touchx = e.stageX - penWidth / 2;

                        if (touchx < 0) { // 不让元素超过左边
                            touchx = 0;
                        }
                        if (touchx > stageWidth - penWidth) {// 不让元素超过右边
                            touchx = stageWidth - penWidth;
                        }
                        that.mainpen.penE.x = touchx;
                        break;
                }
            }

            money = function (x, type) {
                this.x = x;
                this.y = 0;
                this.type = type;
                this.status = 0;//0正在掉落，1落进盆，2没接住
                this.m = cBitmap(moneyEnum[this.type].image);
                this.dropM = new createjs.Text(0, '50px Arial', '#ffd200');
            };

            money.prototype.draw = function () { // 绘制掉落元素
                if (this.status === 0) {
                    this.m.x = this.x;
                    this.m.y = this.y;
                    stage.addChild(this.m);
                }
                // console.log(1);
            };
            money.prototype.drop = function () {

                speed = moneyEnum[this.type].speed;

                if (hard === 2) {
                    speed *= 3;
                }
                this.y += speed;

                // 如果碰到接住元素
                // 得分判断
                if (
                    this.status === 0
                    && this.y >= penY - 50
                    && this.x + 45 > body.mainpen.penE.x
                    && this.x < body.mainpen.penE.x + penWidth / 2 + 80
                ) {//判断是否掉入盆中
                    this.status = 1;
                    // person.gotoAndStop('stand');
                    person.gotoAndPlay('run'); // 吃到东西时改变动作
                    var tm = new TimelineMax(); //构造tweenmax
                    if (moneyEnum[this.type].value > 0) { // 大于0显示正数字，不然是负数
                        scoreValue = '+' + moneyEnum[this.type].value;
                    } else {
                        scoreValue = moneyEnum[this.type].value;
                    }
                    this.dropM.text = scoreValue;//接住元素后显示当前元素的分数
                    this.dropM.x = this.x + 40;
                    this.dropM.y = penY - 50 - 117 + 20;

                    if (scoreValue == "-20") {
                        this.dropM.color = "#b1b1b1";
                    } else if (scoreValue == "+10") {
                        this.dropM.color = "#41ea87";
                    } else if (scoreValue == "+20") {
                        this.dropM.color = "#40e9e7";
                    } else if (scoreValue == "+30") {
                        this.dropM.color = "#0023e1";
                    } else if (scoreValue == "+40") {
                        this.dropM.color = "#ee4015";
                    } else if (scoreValue == "+70") {
                        this.dropM.color = "#d1c347";
                    }


                    stage.addChild(this.dropM);
                    score += moneyEnum[this.type].value;//记录总分数
                    // 播放声音
                    // alert("播放音效")
                    $("#music-ding")[0].currentTime = 0;
                    $("#music-ding")[0].play();
                    var that = this;
                    tm.to(this.dropM, .3, {
                        alpha: 0, onComplete: function () { // 分数的淡出动画
                            stage.removeChild(that.dropM); //删除接住后的元素
                            tm = null;
                        }
                    });
                    stage.removeChild(this.m); // 删除接住的元素

                } else if (this.y >= stageHeight) { // 超过指定高度则为没接住的元素
                    stage.removeChild(this.m); // 删除超过屏幕的元素
                    this.status = 2;
                }
                this.draw();
            };

            var addInterval = setInterval(function () {
                if (isEnd) { // 判断是否在游戏中

                    var r = Math.random() * stageWidth - 80;
                    var r1 = Math.random() * stageWidth - 80;

                    if (r <= 0) { // 不让掉落元素在屏幕外出现
                        r = 10
                    }
                    if (r1 <= 0) { // 不让掉落元素在屏幕外出现
                        r1 = 10
                    }
                    if (hard === 0) {
                        that.addMoney(r);

                    }
                    if (hard > 0) {
                        that.addMoney(r);
                        if (Math.random() > 0.5) {
                            that.addMoney(r1);
                        }
                    }
                } else { // 游戏结束不再往数组中添加掉落元素
                    clearInterval(addInterval)
                }
            }, 1000);

        }
        Body.prototype.addMoney = function (x) { // 将要掉落的元素放入数组中
            var random = Math.floor(Math.random() * 8);
            if (random === 0 && cxs_num_left >= 0 && isEnd) {
                this.moneyList.push(new money(x, "lightblue20"));
            }
            else if (random === 1 && msb_num_left >= 0 && isEnd) {
                this.moneyList.push(new money(x, "green10"));
            }
            else if (random === 2 && sxd_num_left >= 0 && isEnd) {
                this.moneyList.push(new money(x, "blue30"));
            }
            else if (random === 3 && zad_num_left >= 0 && isEnd) {
                this.moneyList.push(new money(x, "black_20"));
            }
            else if (random === 4 && love_num_left >= 0 && isEnd) {
                this.moneyList.push(new money(x, "red40"));
            }
            else if (random === 5 && lumi_num_left >= 0 && isEnd) {
                this.moneyList.push(new money(x, "gold70"));
            }
            else if (random === 7 && zad_num_left >= 0 && isEnd && hard > 0) {
                this.moneyList.push(new money(x, "black_20"));
            }
            // else if (random === 6 && bodyspa_num_left >= 0 && isEnd) {
            //     this.moneyList.push(new money(x, "bodyspa"));
            // }
            // else if (random === 8 && zad_num_left >= 0 && isEnd && hard > 0) {
            //     this.moneyList.push(new money(x, "black_20"));
            // }
            // else if (random === 9 && zad_num_left >= 0 && isEnd && hard > 0) {
            //     this.moneyList.push(new money(x, "black_20"));
            // }
        };

        Body.prototype.draw = function () {

            this.moneyList.forEach(function (item) {
                item.drop();
            });
            // this.mainpen.draw();
            f.text = score;
        };

        window.Body = Body;
        window.money = money;
        window.pen = pen;

    }

    function stageBreakHandler(event) {
        console.log("stageBreakHandler<<");
        stageWidth = document.documentElement.clientWidth;
        stageHeight = document.documentElement.clientHeight;
        //外部元素自适应
        canvas.width = stageWidth;
        canvas.height = stageHeight;

        if (stageWidth / stageHeight > 0.62) {
            stageScale = stageWidth / 750;//宽度自适应；
            stageScale = 1;//宽度自适应；
            container.scale = stageScale;
            p1C.scale = stageScale;
            p1C.scale = 1;
            console.log('scale1<<<', stageScale);
        } else {
            stageScale = stageHeight / 1206;
            stageScale = 1;

            container.scale = stageScale;
            container.x = (stageWidth - 750 * container.scaleX) / 2;// 高度自适应时解开这个注释 保证图片居中
            console.log('scale2<<<', stageScale);
        }

        penY = stageHeight - penHeight;

        stage.update();
    }
    function loadFun() {

        loadC = new createjs.Container();
        loadP = new createjs.Shape();
        loadP.graphics.beginFill('#000').drawRect(0, 0, stageWidth, stageHeight);
        loadT = new createjs.Text('0%', '30px Arial', '#fff');
        loadT.x = stageWidth / 2;
        loadT.y = stageHeight / 2;
        loadT.textAlign = 'center';
        loadT.textBaseline = 'middle';
        stage.addChild(loadC);
        loadC.addChild(loadP, loadT);

        load = new createjs.LoadQueue(false);

        // createjs-animate.Sound.alternateExtensions = ["mp3"];
        // createjs-animate.Sound.registerSound('html/sound/music.mp3','sound');

        load.addEventListener("progress", progressHandler);
        load.addEventListener("complete", completeHandler);
        load.loadManifest([
            { src: "html/images/accent.png", id: "accent" },
            { src: "html/images/activity_btn.png", id: "activity_btn" },
            { src: "html/images/activity_page_bg.png", id: "activity_page_bg" },
            { src: "html/images/activity_page_btn.png", id: "activity_page_btn" },
            { src: "html/images/ageLocme.png", id: "ageLocme" },
            { src: "html/images/bodyspa.png", id: "bodyspa" },
            { src: "html/images/first_page_bg.jpg", id: "first_page_bg" },
            { src: "html/images/game_bg.jpg", id: "game_bg" },
            { src: "html/images/love.png", id: "love" },
            { src: "html/images/lumispa.png", id: "lumi" },
            { src: "html/images/lunTai.png", id: "lunTai" },
            { src: "html/images/me.png", id: "me" },
            { src: "html/images/page01_car.png", id: "page01_car" },
            { src: "html/images/page01_person.png", id: "page01_person" },
            { src: "html/images/page01_s.png", id: "page01_s" },
            { src: "html/images/page01_t.png", id: "page01_t" },
            { src: "html/images/page01_title.png", id: "page01_title" },
            { src: "html/images/ramonaflowers_multiple.png", id: "ramonaflowers_multiple" },
            { src: "html/images/result_again.png", id: "result_again" },
            { src: "html/images/result_bg.png", id: "result_bg" },
            { src: "html/images/result_header.png", id: "result_header" },
            { src: "html/images/result_share.png", id: "result_share" },
            { src: "html/images/run_line.png", id: "run_line" },
            { src: "html/images/score_bg.png", id: "score_bg" },
            { src: "html/images/facespa.png", id: "facespa" },
            { src: "html/images/start_btn.png", id: "start_btn" },
            { src: "html/images/time_bg.png", id: "time_bg" },
            { src: "html/images/units-icons.png", id: "units-icons" },
            { src: "html/images/person.png", id: "person" },
            { src: "html/images/logo.png", id: "logo" },
            { src: "html/images/userinfo_close_btn.png", id: "userinfo_close_btn" },
        ]);
    }
    function handleFileLoad(evt) {
        if (evt.item.type === "image") { images[evt.item.id] = evt.result; }
    }
    function progressHandler(event) {
        loadT.text = Math.floor(event.progress * 99) + '%';
    }
    function completeHandler() {
        var tm = new TimelineMax();
        loadT.text = 100 + '%';
        event.currentTarget.removeEventListener("fileload", handleFileLoad);
        event.currentTarget.removeEventListener("progress", progressHandler);
        event.currentTarget.removeEventListener("complete", completeHandler);
        // console.log('complete');
        page1();

        $('.u-globalAudio').css('display', 'block');
        tm.to(loadC, .5, {
            alpha: 0, onComplete: function () {

            }
        })
    }
    // 第一页
    function page1() {

        container.addChild(p1C);

        p1Bg = cBitmap('html/images/first_page_bg.jpg');

        var image = new Image();
        image.src = "html/images/first_page_bg.jpg";
        image.onload = handlerImageLoad;

        function handlerImageLoad(event) {
            // 加载背景图
            console.log("加载背景", event.target);
            var p1Bg = new createjs.Bitmap(event.target);
            p1Bg.x = stageWidth - p1Bg.getBounds().width >> 1;
            p1Bg.y = stageHeight - p1Bg.getBounds().height >> 1;
            p1C.addChild(p1Bg);

            other();
        }

        function other() {

            // logo
            p1Logo = cBitmap(load.getResult('logo'));
            p1Logo.scaleX = p1Logo.scaleY = 0.5;
            p1Logo.x = stageWidth - (p1Logo.getBounds().width >> 1) - (p1Logo.getBounds().width >> 2) - 50;
            p1Logo.y = 0;


            p1Title = cBitmap(load.getResult('page01_title')); //第一页标题
            p1Title.scaleX = p1Title.scaleY = 0.5;
            p1Title.x = stageWidth / 2 - p1Title.getBounds('width').width / 2 + 70;
            p1Title.y = 0 - (p1Title.getBounds().height / 2 / 2) + 40;

            p1T = cBitmap(load.getResult('page01_t')); //第一页标题下文字
            p1T.x = stageWidth / 2 - p1T.getBounds('width').width / 2;
            p1T.y = 170;

            p1Car = cBitmap(load.getResult('page01_car')); //第一页车子
            p1Car.scaleX = p1Car.scaleY = 0.5;
            // console.log(p1Car.getBounds().width / 2);
            p1Car.x = 0 - (p1Car.getBounds().width / 2) / 2;
            p1Car.y = 0 - (p1Car.getBounds().height / 2) / 2;
            // p1Car.x = 0;
            // p1Car.y = 0;

            p1S = cBitmap(load.getResult('page01_s')); //第一页车子后面礼物堆
            p1S.scaleX = p1S.scaleY = 0.5;
            p1S.x = 0;
            p1S.y = stageHeight - (605 / 2);

            p1P = cBitmap(load.getResult('page01_person')); //第一页最下方小人
            p1P.y = stageHeight - p1P.getBounds('height').height;

            p1StartBtn = cBitmap(load.getResult('start_btn')); //第一页开始游戏按钮

            console.log("舞台宽度", stageWidth);
            // p1StartBtn.x = stageWidth - p1StartBtn.getBounds('width').width;
            // 计算中间为位置
            p1StartBtn.x = (stageWidth / 2) - (p1StartBtn.getBounds('width').width / 2);
            p1StartBtn.y = stageHeight - p1StartBtn.getBounds('height').height - 180;

            p1RuleBtn = cBitmap(load.getResult('activity_btn')); //第一页查看规则按钮
            p1RuleBtn.x = (stageWidth - p1RuleBtn.getBounds('width').width) / 2;
            p1RuleBtn.y = stageHeight - p1RuleBtn.getBounds('height').height - 50;



            activityPB = cBitmap(load.getResult('html/images/activity_page_bg.png')); //规则图片
            console.log(activityPB);
            activityPB.alpha = 0;
            activityPB.x = (stageWidth - activityPB.getBounds().width) >> 1;
            activityPB.y = (stageHeight - activityPB.getBounds().height) >> 1;
            activityPBtn = cBitmap(load.getResult('userinfo_close_btn')); // 查看规则按钮
            activityPBtn.x = activityPB.x + activityPB.getBounds().width - (activityPBtn.getBounds().width >> 1) - 10;
            activityPBtn.y = activityPB.y + 90;
            activityPBtn.alpha = 0;

            // 设置圆心的点
            setCenterC(p1Logo)
            setCenterC(p1Title);
            setCenterC(p1T);
            setCenterC(p1Car);
            setCenterC(p1S);

            // 一些尺寸做细节调整
            if (stageWidth / stageHeight > 0.62) {
                p1P.y = stageHeight - p1P.getBounds('height').height + 70;
                if (stageHeight <= 1108) {
                    // p1P.x = 0;
                    // p1P.y = stageHeight - p1P.getBounds('height').height + 100;
                    // p1P.scale = .8;
                }
            } else {
                // p1Title.scale = .9;
                // p1T.scale = .9;
                // p1Car.scale = 0.85;
                if (stageHeight <= 1217) {
                    // p1P.y = stageHeight - p1P.getBounds('height').height + 50;
                    // p1P.scale = .9;
                }
            }

            stage.addChild(p1P);
            stage.addChild(p1StartBtn, p1RuleBtn);

            p1C.addChild(p1Logo, p1Title, p1Car);

            p1C.addChild(activityPB);
            p1C.addChild(activityPBtn);

            // 首页动画
            var tm = new TimelineMax();
            var tm2 = new TimelineMax();
            var tm3 = new TimelineMax();
            var tm4 = new TimelineMax();
            var tm5 = new TimelineMax();

            tm.from(p1Logo, 0.8, { alpha: 0 });

            tm.from(p1Title, .5, { alpha: 0, rotation: 120 });
            tm.from(p1T, .3, { alpha: 0 });
            tm.from(p1Car, .3, { alpha: 0, regX: 100 });
            tm.from(p1S, .5, { bezier: [{ alpha: 1, regY: 100 }, { alpha: 0, regY: 200 }], ease: Power1.easeInOut });
            tm.from(p1P, .5, { alpha: 0, regY: -100 });
            tm.from(p1StartBtn, .3, { alpha: 0, regX: -50 });
            tm.from(p1RuleBtn, .3, { alpha: 0, regX: -50 });

            p1StartBtn.addEventListener('pressup', function () { // 点击开始游戏
                console.log('start game');
                container.removeChild(p1C); //删除第一页
                isEnd = true;
                body = new window.Body();
                pen.prototype.draw(); // 绘制接金币元素
                stage.addChild(timeBg, scoreBg); // 渲染时间和分数背景
                // stage.addChild(timeBg, scoreBg, runLine); // 渲染时间和分数背景
                gameTimeFun(); // 时间开始
                //右上角分数
                f.x = stageWidth - 70 - 10;
                f.y = 50 + 20;
                stage.addChild(f);// 渲染右上角分数
                stage.addChild(person);// 渲染跑步小人
                stage.removeChild(p1P, p1RuleBtn, p1StartBtn);
            });
            p1RuleBtn.addEventListener('pressup', function () { // 点击查看游戏规则
                activityPB.alpha = 1;
                activityPBtn.alpha = 1;
                p1StartBtn.alpha = 0;
                p1RuleBtn.alpha = 0;
                p1P.alpha = 0;
            });
            activityPBtn.addEventListener('pressup', function () { // 点击开始游戏
                activityPB.alpha = 0;
                activityPBtn.alpha = 0;
                p1StartBtn.alpha = 1;
                p1RuleBtn.alpha = 1;
                p1P.alpha = 1;
            });
        }


    }

    // 结果页面
    function resultP() {
        $('.restart-box').css('display', 'flex');
        $('.again')[0].addEventListener('click', function () { // 重新开始游戏
            console.log("重新开始");
            paused = createjs.Ticker.paused = true; // 再次开启update

            $('.restart-box').css('display', 'none'); // 隐藏结果页
            $('.share-page').css('display', 'none'); // 隐藏结果页
            $('.userrank-page').css('display', 'none'); // 隐藏结果页
            clearuserinfo();

            body.moneyList = []; // 清空数组
            // 重新设置画布背景和游戏元素
            container = new createjs.Container();
            stage.addChild(container);
            bg = cBitmap('html/images/game_bg.jpg');
            container.addChild(bg);
            stage.addChild(timeBg, scoreBg);

            stageBreakHandler();

            pen.prototype.draw(); // 绘制接金币元素
            body = new window.Body();
            isEnd = true; // 再次开启游戏
            hard = 0; // 难度重置为0
            // time = 5; // 重置时间
            time = 30; // TODO 重置时间
            score = 0; //  重置分数
            gameTimeFun(); // 重新开启时间
            stage.addChild(f);// 重新渲染右上角分数
            stage.addChild(person);// 重新渲染跑步小人
        });

        // 查看排名按钮
        $('.share')[0].addEventListener('click', function () {
            console.log("显示提交信息界面<<<");
            if (isRegister) {
                // 注册过了就直接显示排名
                doshowrank();
            } else {
                // 显示用户信息提交弹层
                $('.share-page').css('display', 'flex');
                $('.restart-box').css('display', 'none');
            }

        });

        // 用户信息提交弹层
        // 关闭
        $('#userinfo-close')[0].addEventListener('click', function () {
            $('.share-page').css('display', 'none');
            $('.restart-box').css('display', 'flex');
            clearuserinfo();
        });
        //提交
        $('#userinfo-commit')[0].addEventListener('click', function () {
            doCommit();
        });
    }

    function clearuserinfo() {
        $("#username").val("");
        $("#userphone").val("");
    }
    function dogetuserinfo() {
        return {
            username: $("#username").val(),
            userphone: $("#userphone").val()
        }
    }
    function doCommit() {
        const { username, userphone } = dogetuserinfo();
        // console.log(username)
        // console.log(userphone)
        // console.log(score);
        // alert(username + "==" + userphone);
        // 校验
        if (!username) {
            alert('请填写您的姓名');
            return;
        }
        if (!userphone) {
            alert('请填写您的手机号');
            return;
        }
        if (!checkphone(parseInt(userphone))) {
            alert('请填写正确的手机号');
            return;
        }
        // 提交用户信息
        commitUserInfo(username, userphone, score, function (data) {
            alert("提交成功2" + JSON.stringify(data));
            if (data.result == "true") {
                doshowrank();
            } else {
                alert("[1]提交失败 请稍后再试...");
            }
        }, function (err) {
            alert("[0]提交失败 请稍后再试...");
        });
    }
    function checkphone(number) {
        //验证手机号码
        if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(number))) {
            return false;  //不满足条件
        } else {
            return true;//满足条件
        }
    }

    // 用户排行
    function doshowrank() {
        // TODO 获取用户排行
        getRankList(function (data) {
            if (data.result == "true") {
                /**
                 * data:
                 * {
                 * item:[{userName:"", mobile:"", score:""}]
                 * 
                 * }
                 */
                if (data.data && data.data.item) {
                    var ranklist = data.data.item;
                    // var ranklist = [
                    //     { userName: "teset1", mobile: "18868807124", score: "666" },
                    //     { userName: "teset2", mobile: "18868807121", score: "664" },
                    //     { userName: "teset3", mobile: "18868807122", score: "663" },
                    // ]
                    buildRankList(ranklist);
                }
                $('.userrank-page').css('display', 'flex');
                $('.share-page').css('display', 'none');
            } else {
                alert('[1]获取排行失败');
            }
        }, function (err) {
            alert('[0]获取排行失败')
        });

        clearuserinfo();

        getScore(score, function (datas) {

        });
    }

    function buildRankList(ranklist) {
        var listbox = $("#userrank-list").html("");
        for (let i = 0; i < 5; i++) {
            var name = "";
            var score = "";
            if (ranklist[i]) {
                if (ranklist[i].userName && ranklist[i].userName != null) {
                    name = ranklist[i].userName;
                }
                if (ranklist[i].score && ranklist[i].score != null) {
                    score = ranklist[i].score;
                }
            }
            if (score) {
                var li = $(`<li><span class="rank-img"><img src="./html/images/rank${i + 1}.png" alt=""></span><span class="rank-name">${name}</span><span class="rank-score">${score}分</span></li>`);
                listbox.append(li);
            } else {
                var li = $(`<li><span class="rank-img"><img src="./html/images/rank${i + 1}.png" alt=""></span><span class="rank-name">暂无</span><span class="rank-score">暂无</span></li>`);
                listbox.append(li);
            }
        }
        buildMyScore();
    }
    function buildMyScore() {
        $("#curt-score").html("");
        $("#curt-rank").html("");
        $("#curt-score").html(score);
        $("#curt-rank").html("233");
    }

    // 用户排行页面 重新开始
    $('#userrank-again')[0].addEventListener('click', function () { // 重新开始游戏
        console.log("重新开始2");
        paused = createjs.Ticker.paused = true; // 再次开启update

        $('.restart-box').css('display', 'none'); // 隐藏结果页
        $('.share-page').css('display', 'none'); // 隐藏结果页
        $('.userrank-page').css('display', 'none'); // 隐藏结果页
        clearuserinfo();

        body.moneyList = []; // 清空数组
        // 重新设置画布背景和游戏元素
        container = new createjs.Container();
        stage.addChild(container);
        bg = cBitmap('html/images/game_bg.jpg');
        container.addChild(bg);
        stage.addChild(timeBg, scoreBg);

        stageBreakHandler();

        pen.prototype.draw(); // 绘制接金币元素
        body = new window.Body();
        isEnd = true; // 再次开启游戏
        hard = 0; // 难度重置为0
        time = 5; // 重置时间
        // time = 30; // TODO 重置时间
        score = 0; //  重置分数
        gameTimeFun(); // 重新开启时间
        stage.addChild(f);// 重新渲染右上角分数
        stage.addChild(person);// 重新渲染跑步小人
    });

    function gameTimeFun() {
        clearInterval(timer);
        gameTime = new createjs.Text(time, 'bold 24px Arial', '#fff');
        gameTime.x = 30 + 25;
        gameTime.y = 50 + 20;
        stage.addChild(gameTime); // 时间显示在页面上
        timer = setInterval(function () { // 倒计时
            time -= 1;
            gameTime.text = time;
            // stage.addChild(gameTime);
            if (time <= 20) {
                hard = 1;
            }
            if (time <= 10) {
                hard = 2;
                bgSpeed = 8;
            }
            if (time <= 0) { // 时间到则停止游戏
                gameTime.text = 0;
                stage.addChild(gameTime);
                stage.update();
                isEnd = false; // 停止游戏
                bgSpeed = 4;
                stage.removeAllEventListeners();
                paused = createjs.Ticker.paused = false; // 停止update
                $('.current-score').text(score); // 结果页显示自己所玩分数
                console.log(score); // 结果分数
                clearInterval(timer);
                // 显示时间到了
                document.querySelector("#timeend").style.display = "flex";
                setTimeout(() => {
                    document.querySelector("#timeend").style.display = "none";
                    resultP(); // 显示结果页
                }, 1000);
            }
        }, 1000)
    }
    function cBitmap(img) {
        return new createjs.Bitmap(img)
    }
    //TODO 因为微信游览器不会自动播放音乐，用此函数自动播放音乐
    // document.addEventListener('DOMContentLoaded', function () {
    //     alert(1)
    //     document.addEventListener("WeixinJSBridgeReady", function () {
    //         alert(2)
    //         music.play();
    //     }, false);
    // });
    document.addEventListener("WeixinJSBridgeReady", function () {
        alert(2)
        music.load();
        music.play();
    }, false);
    // function autoPlayAudio() {
    //     wx.config({
    //         debug: false
    //         , appId: ''
    //         , timestamp: 1
    //         , nonceStr: ''
    //         , signature: ''
    //         , jsApiList: []
    //     });
    //     wx.ready(function () {
    //         alert("wx1")
    //         music.load();
    //         music.play();
    //     });
    // }
    // autoPlayAudio();

    //音乐播放
    $(".u-globalAudio").on('click', function () {
        // var audio = $("#music")[0];
        if ($(this).hasClass("z-play")) {
            $(this).removeClass("z-play");
            // createjs-animate.Sound.stop('sound')
            music.pause();
        }
        else {
            $(this).addClass("z-play");
            music.play();
            // createjs-animate.Sound.play('sound', {loop: -1})
        }
    });

    function setCenterC(ele) { // 设置原点
        ele.x = ele.x + ele.getBounds('width').width / 2;
        ele.y = ele.y + ele.getBounds('height').height / 2;
        ele.regX = ele.getBounds('width').width / 2;
        ele.regY = ele.getBounds('height').height / 2;
    }

    function getUserFail(params) {
        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(local) + "&response_type=code&scope=snsapi_base&state=rx&connect_redirect=1#wechat_redirect";
    }
    // 提交用户信息和分数
    function commitUserInfo(username, userphone, score, success, fail) {
        alert("提交用户信息和分数name<<" + username + " phone<<" + userphone + " score<<" + score);
        var obj = {
            UserName: username + "",
            Mobile: userphone + "",
            Score: score + ""
        }
        // alert(url + usersApi);
        // alert(TOKEN);

        $.ajax({
            url: url + usersApi,
            type: 'POST',
            data: JSON.stringify(obj),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Bearer ' + TOKEN);
            },
            success: function (data) {
                // alert("提交信息成功1" + JSON.stringify(data));
                success && success(data);
            },
            error: function (err) {
                fail && fail(err);
            }
        })
    }
    // 更新分数
    function getScore(score, success, fail) {
        $.ajax({
            url: url + scoreApi,
            type: 'GET',
            data: {
                score: score
            },
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Bearer ' + TOKEN);
            },
            success: function (data) {
                alert("更新分数成功" + JSON.stringify(data));
                success && success(data);
            },
            error: function (err) {
                alert("更新分数失败" + JSON.stringify(err));
                fail && fail(err);
            }
        })
    }
    // 获取排行
    function getRankList(success, fail) {
        $.ajax({
            url: url + rankApi,
            type: 'POST',
            contentType: 'application/json;charset=utf-8',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Bearer ' + TOKEN);
            },
            success: function (data) {
                alert("获取列表成功" + JSON.stringify(data));
                success && success(data);
            },
            error: function (err) {
                alert("获取列表失败" + JSON.stringify(err));
                fail && fail();
            }
        });
    }
    // 获取用户信息 得到token
    function getUser(success, fail) {
        const local = window.location.href;
        const code = request("code");
        if (code == "" || code == undefined || code == null) { // 没有code并且是首页才重新跳转获取code
            if (window.location.href.indexOf('index.html') > -1) {
                window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(local) + "&response_type=code&scope=snsapi_base&state=rx&connect_redirect=1#wechat_redirect"
            }
        } else {
            $.ajax({
                url: url + userinfoApi + '?code=' + code,
                method: 'GET',
                dataType: "json",
                success: function (res) {
                    alert('用户信息<<' + JSON.stringify(res));
                    if (res && res.result == "true") {
                        if (res.data.playTime) {
                            isRegister = true;
                        }
                        TOKEN = res.data.token;
                        // alert(TOKEN)
                        if (res.data.token) {
                            TOKEN = res.data.token;
                            success && success();
                        } else {
                            fail && fail();
                        }
                    } else {
                        fail() && fail();
                    }
                },
                error: function (err) {
                    alert("获取信息错误<<<" + JSON.stringify(err))
                    fail && fail();
                }
            });
        }
    }
    // 解析url
    function request(paras) {
        var url = location.href;
        alert("跳转的url" + url);
        var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
        var paraObj = {};
        for (i = 0; j = paraString[i]; i++) {
            paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
        }
        var returnValue = paraObj[paras.toLowerCase()];

        if (typeof (returnValue) == "undefined") {
            return "";
        } else {
            return returnValue;
        }
    }

    init();
    // getUser(getUserSuccess, getUserFail);
    function getUserSuccess() {
        init();
    }
}
